package com.zl.cms.service;

import com.zl.basic.CommonUtil.Check;
import com.zl.basic.model.SystemContext;
import com.zl.cms.dao.IChannelDao;
import com.zl.cms.model.Channel;
import com.zl.cms.model.ChannelTree;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.List;

/**
 * User: zl email:c3tc3tc3t@126.com Date: 14-2-2 Time: 下午3:56
 */
@Service("channelService")
public class ChannelService implements IChannelService {
  private IChannelDao channelDao;

  public IChannelDao getChannelDao() {
    return channelDao;
  }

  @Inject
  public void setChannelDao(IChannelDao channelDao) {
    this.channelDao = channelDao;
  }

  @Override
  public void add(Channel channel, Integer pid) {
    Integer orders = channelDao.getMaxOrderByParent(pid);
    if (null != pid && pid > 0) {
      Channel pc = channelDao.load(pid);
      Check.checkAnyNull(pc, "要添加栏目的父栏目不存在");
      channel.setParent(pc);
    }

    channel.setOrders(orders + 1);
    channelDao.add(channel);
  }

  @Override
  public void update(Channel channel) {
    channelDao.update(channel);
  }

  @Override
  public void delete(int id) {
    // Todo 1.判断是否存在子栏目
    List<Channel> cs = channelDao.listByParent(id);
    Check.checkIsNull(cs, "要删除的栏目有子栏目，无法删除");
    // Todo 2.判断是否存在文章
    // Todo 3.要删除和组的关系
    channelDao.delete(id);
  }

  @Override
  public void clearTopic(int id) {
    // Todo 实现了文章模块之后才实现该方法
  }

  @Override
  public Channel load(int id) {
    return channelDao.load(id);
  }

  @Override
  public List<Channel> listByParent(Integer id) {
    /*
     * String sortkey = SystemContext.getSortkey(); if (sortkey == null ||
     * "".equals(sortkey.trim())) { SystemContext.setSortkey("orders");
     * SystemContext.setOrder("asc"); }
     */
    return channelDao.listByParent(id);
  }

  @Override
  public List<ChannelTree> generateTree() {
    return channelDao.generateTree();
  }

  @Override
  public List<ChannelTree> generateTreeByParent(Integer pid) {
    return channelDao.generateTreeByParent(pid);
  }

  @Override
  public void updateSort(Integer[] ids) {
    channelDao.updateSort(ids);
  }

  @Override
  public List<Channel> listPublishChannel() {
    return channelDao.listPublishChannel();
  }
}
